<template>
	<view class="bg-background min-h-[100vh]">
		<view class="p-[16rpx]">
			<Address v-model="params" :address="order.address" :shop="order.shop"></Address>
			<view class="mt-[16rpx] bg-white rounded-[8rpx]">
				<view>
					<view class="p-[36rpx] border-b border-background flex" v-for="item in order.carVo" :key="item.id">
						<up-image :src="$setBaseUrl(item.icon)" width="128rpx" height="128rpx"></up-image>
						<view class="text-[22rpx] flex-1 ml-[24rpx]">
							<view class="text-[26rpx]">{{ item.name }}</view>
							<view class="mt-[24rpx] text-gray line-clamp-2 max-w-[310rpx]">{{ item.brief }}</view>
						</view>
						<view class="text-[#999] flex flex-col justify-between">
							<view class="text-[28rpx] text-[#E55800]">¥{{ item.price }}</view>
							<view class="text-[22rpx] line-through">¥{{ item.demoPrice }}</view>
							<view class="text-[26rpx]">×{{ item.num }}</view>
						</view>
					</view>
				</view>
				<view class="text-end p-[36rpx] text-[26rpx]">
					<text>共{{ order.num }}件商品，合计:</text>
					<text class="text-[38rpx] font-bold">¥{{ order.total?.toFixed(2) }}</text>
				</view>
			</view>
			<view class="mt-[16rpx] flex items-center justify-between p-[24rpx] bg-white rounded-[8rpx] text-[26rpx]">
				<view class="">支付方式</view>
				<view class="flex items-center">
					<up-image :src="wx" width="48rpx" height="48rpx"></up-image>
					<view class="text-gray ml-[16rpx]">微信支付</view>
					<up-icon name="arrow-right" color="#666" size="16"></up-icon>
				</view>
			</view>
		</view>
		<view class="h-[96rpx]"></view>
		<view class="h-[96rpx] w-full fixed bottom-0 bg-white flex items-center justify-between">
			<view class="px-[32rpx] leading-none">
				<view class="text-[#333]">
					<text class="text-[22rpx] mr-[8rpx]">应付:</text>
					<text class="text-[32rpx] font-bold">¥{{ order.total?.toFixed(2) }}</text>
				</view>
			</view>
			<view class="flex items-center justify-center bg-second text-white text-[34rpx] w-[276rpx] h-full" @click="orderSubmit">立即支付</view>
		</view>
	</view>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue';
import wx from '@/static/wx.png';
import { checkout, getTempOrder, groupOrder, orderGood, orderPay, submitOrder } from '@/config/api/order';
import { onShow, onLoad } from '@dcloudio/uni-app';
import useShop from '@/hooks/useShop';
import useAddress from '@/hooks/useAddress';
import { timeFormat } from '@/uni_modules/uview-plus';
import utils from '@/utils/utils';
onLoad(async ({ groupId }) => {
	if (groupId) {
		params.groupId = groupId;
	}
	await getDefault(); // 获取默认地址
	params.address = defaultAddress.value.id || null; // 设置默认地址
});
onShow(async () => {
	await getCurrentShop(); // 获取最近或者之前选择的店铺
	params.shopId = currentShop.value.id || null; // 设置最近或者之前选中的店铺
	// await orderCheckout(); // 获取订单信息
});
const { getCurrentShop, currentShop } = useShop(); // 店铺
const { getDefault, defaultAddress } = useAddress(); // 地址
const { order, orderCheckout, params } = useCheckout(); // 订单生成
const { orderSubmit } = useOrder(); // 提交订单
function useCheckout() {
	const order = ref({}); // 订单详情
	const params = reactive({
		type: 0, // 订单类型 0堂食 1外卖 2商城
		address: null, // 订单地址
		shopId: null, // 商铺id
		groupId: null
	});
	//订单
	const orderCheckout = async () => {
		try {
			const res = await groupOrder(params);
			if (res.code == 200) {
				getOrderInfo();
			}
		} catch (e) {
			//TODO handle the exception
		}
	};
	//获取当前订单信息
	const getOrderInfo = async () => {
		try {
			const res = await getTempOrder();
			if (res.code == 200) {
				order.value = res.data;
			}
		} catch (e) {
			//TODO handle the exception
		}
	};
	watch(
		() => params,
		() => {
			if ((params.type == 0 && params.shopId) || (params.type == 1 && params.address)) {
				orderCheckout();
			}
		},
		{
			deep: true
		}
	);
	return {
		order,
		params,
		orderCheckout,
		getOrderInfo
	};
}
function useOrder() {
	const orderSubmit = async () => {
		try {
			const { data } = await submitOrder();
			const res = await orderPay(data.appOrder.orderSn);
			if (res.code == 200) {
				if (!res.data.unifiedOrderResult) {
					utils.showToast('支付参数为空');
					return;
				}
				await chooseWXPay(res.data.unifiedOrderResult);
			}
		} catch (e) {
			//TODO handle the exception
		}
	};
	const chooseWXPay = (prepayInfo) => {
		return new Promise((resolve, reject) => {
			jWeixin.chooseWXPay({
				appId: prepayInfo.appId,
				timestamp: prepayInfo.timeStamp,
				nonceStr: prepayInfo.nonceStr,
				package: prepayInfo.packageValue,
				signType: prepayInfo.signType,
				paySign: prepayInfo.paySign,
				success: () => {
					utils.showToast('下单成功');
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/drinkOrder/drinkOrder'
						});
					}, 500);
					resolve();
				},
				fail: () => {
					utils.showToast('支付失败');
					reject();
				}
			});
		});
	};
	// 检测支付环境中的 WeixinJSBridge
	function wxpay(data) {
		if (typeof WeixinJSBridge == 'undefined') {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady(data), false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady(data));
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(data));
			}
		} else {
			onBridgeReady(data);
		}
	}
	function onBridgeReady(data) {
		return new Promise((resolve, reject) => {
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest',
				{
					// 传入第一步后端接口返回的核心参数
					appId: data.appid, //公众号
					timeStamp: data.timeStamp, //时间戳
					nonceStr: data.nonceStr, //随机串
					package: 'prepay_id=' + data.prepayId, //prepay_id
					signType: 'MD5', //微信签名方式RSA
					paySign: data.sign //微信签名
				},
				(res) => {
					// 支付成功
					if (res.err_msg == 'get_brand_wcpay_request:ok') {
						utils.showToast('下单成功');
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/drinkOrder/drinkOrder'
							});
						}, 500);
						resolve();
					}
					// 支付过程中用户取消
					if (res.err_msg == 'get_brand_wcpay_request:cancel') {
						utils.showToast('用户取消支付');
						reject();
					}
					// 支付失败
					if (res.err_msg == 'get_brand_wcpay_request:fail') {
						utils.showToast('支付失败');
						reject();
					}
					if (res.err_msg == '调用支付JSAPI缺少参数：total_fee') {
						utils.showToast('缺少参数');
						reject();
					}
				}
			);
		});
	}
	return {
		orderSubmit
	};
}
</script>

<style scoped lang="scss">
.roundness {
	@apply bg-white w-[24rpx] h-[24rpx] rounded-full absolute  right-0 translate-x-[50%];
}
</style>
